// pages/registration/sharetovisitor.js
var Constant = require('../../utils/constant.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showShip: true,
    roleList: ['业主配偶', '业主父母', '业主兄弟', "业主子女", "业主亲戚", "其他"],
    role: '业主配偶',
    location: '',
    takePicType: 'visitor',
    photoPath: '/images/img_add.png',
    openid: "",
    userType: "longvisitor",
    picBase64:"",
    previewTime: '',
    personId: '',
    personKey:'',
    startTime: '',
    endTime:'',
    userName: '',

    localLists: [],
    userOrgCodelList:[],
    localvalue: '',
    localName: "请选择",
    idCard: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })

    if (options.localLists!=null){
      this.data.localLists = options.localLists.split(",")
      this.data.userOrgCodelList = options.userOrgCodelList.split(",")
    }

    console.log("aaa1", this.data.userOrgCodelList)

    this.setData({
      localLists: this.data.localLists
    })

    if(options.userType){
      this.setData({
        location: options.location,
        openid: options.openid,
        userType: options.userType,
        previewTime: options.timestamp,
        personId: options.personId,
        personKey: options.personKey,
      })
    }
    if (typeof (options.endTime) != "undefined") {
      this.setData({
        startTime: options.startTime,
        endTime: options.endTime,
      })
      console.log('开始时间：', options.startTime, "结束时间：", options.endTime)
    }
    if (this.data.userType != "longvisitor") {
      this.setData({
        showShip: false,
      })
    }
    
    var that = this;
    
    //that.data.personId = "5LP7S55EKwUxOre8sXx";
    //that.data.personKey = "IR72EwVw8S5KHDwngqv";
    wx.request({
      url: Constant.BASEURL + Constant.IS_ID_USED + "&key=" + that.data.personKey,
      method: "GET",
      success(res){
        console.log(res.data)
        if (res.data.respCode != "0"){
          wx.showModal({
            title: '提示',
            content: '该链接已被使用，请业主重新分享',
            showCancel: false,
            success(res){
              if(res.confirm){
                wx.navigateBackMiniProgram()
              }
            }
          })
        }
      },
      fail(err){
        console.log(err)
        wx.showToast({
          title: '系统错误',
          icon: 'none'
        })
      }
    })


    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      console.log(this.data.userInfo)
      //getOpenId(res);
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        wx.login({
          success: function (r) {
            var code = r.code;//登录凭证
            var res = { 'res': { 'encryptedData': encryptedData, 'iv': iv } }
            getOpenId(res, code)
          }
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          wx.login({
            success: function (r) {
              var code = r.code;//登录凭证
              var res = { 'res': { 'encryptedData': encryptedData, 'iv': iv } }
              getOpenId(res, code)
            }
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // var timestamp = Date.parse(new Date());
    // var preTime = this.data.previewTime;
    // if ((timestamp - preTime) > 3 * 60 * 1000){
    //   wx.showModal({
    //     title: '提示',
    //     content: '链接已经失效了，请联系业主重新分享',
    //     showCancel:false,
    //     success: function(res){
    //       if(res.confirm){
    //         wx.navigateBackMiniProgram({
              
    //         })
    //       }
    //     }
    //   })
    // }

    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.photoPath != "/images/img_add.png") {
      this.setData({
        photoPath: currPage.data.photoPath,
      });
      picToBase64(this.data.photoPath, this)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  bindCommunityChange: function (e) {
    this.setData({
      localName: this.data.localLists[e.detail.value],
      localvalue: e.detail.value
    })
  },

  getUserInfo: function (e) {
    console.log(e)
    encryptedData = e.detail.encryptedData;
    iv = e.detail.iv;
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    wx.login({
          success: function (r) {
            var code = r.code;//登录凭证
            var res = { 'res':{'encryptedData': encryptedData, 'iv': iv}}
            getOpenId(res, code)
            }
    })
  },

  idCard: function (e) {
    console.log(e.detail.value)
    this.setData({
      idCard: e.detail.value
    })
  },

  takePicture: function (e) {
    var that = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      success: function (res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: '../takephoto/takephoto?takePicType=' + that.data.takePicType
          })
        } else {
          // wx.navigateTo({
          //   url: '../takephoto/visitorpicture?isRegister='+true,
          // })

          wx.chooseImage({
            count: 1,
            sourceType: ['album'],
            sizeType: 'compressed',
            success: function (res) {
              var picPath = res.tempFilePaths[0];
              console.log(picPath);
              wx.showLoading({
                title: '检测中',
              })
              let manager = wx.getFileSystemManager();
              manager.readFile({
                filePath: picPath,
                encoding: 'base64',
                success: function (res) {
                  //console.log(res.data)
                  that.data.picBase64 = res.data;
                  wx.request({
                    url: Constant.BASEURL + Constant.PICDETECT_URL,
                    method: 'POST',
                    data: { "personphoto": that.data.picBase64 },
                    success: function (res) {
                      wx.hideLoading();
                      var retCode = res.data.obj;
                      if (retCode == "0") {
                        that.setData({
                          photoPath: picPath,
                          imageSelect: true,
                        });
                      } else {
                        let state_msg = "";
                        if (retCode == Constant.STATE_ERROR_FILE_TYPE) {
                          state_msg = '网络请求错误';
                        } else if (retCode == Constant.STATE_ERROR_FILE_INCOMPLETE) {
                          state_msg = '发送的数据不完整，请检查网络连接';
                        } else if (retCode == Constant.STATE_ERROR_FILE_DATA) {
                          state_msg = '不能解析图像数据';
                        } else if (retCode == Constant.STATE_ERROR_FACE_NUM) {
                          state_msg = '人脸数量不正确，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_YIN_YANG) {
                          state_msg = '光线不均匀，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_BORDER) {
                          state_msg = '请将人脸放在画面中央';
                        } else if (retCode == Constant.STATE_ERROR_FACE_RESOLUTION) {
                          state_msg = '人脸太小，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_ANGLE) {
                          state_msg = '人脸角度偏差太大，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_IMAGE_QUALITY) {
                          state_msg = '图像质量太差';
                        } else {
                          state_msg = '未知错误，错误码' + retCode;
                        }

                        wx.showModal({
                          title: '提示',
                          content: state_msg,
                          showCancel: false,
                          success: function (res) { },
                        })
                      }
                    },
                    fail: function (res) {
                      wx.hideLoading();
                      wx.showToast({
                        title: '请检测网络连接',
                        icon: 'none'
                      })
                    }
                  })
                },
                fail: function (res) {
                  console.log(res)
                  wx.showModal({
                    title: '提示',
                    content: '照片无效，请重新选择',
                    showCancel: false,
                    success: function (res) { },
                  })
                }
              })


            },
          })
        }
      }
    })


  },
  bindRoleChange: function (e) {
    this.setData({
      role: this.data.roleList[e.detail.value],
    })
  },
  userName: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },

  buttonNext: function (e) {
    if (app.globalData.openid == ''){
      wx.showToast({
        title: '请登录',
        icon: 'none',
      })
      return;
    }

    if(this.data.showShip){
      if (this.data.idCard != "") {
        console.log(Constant.idCard(this.data.idCard))
        if (!Constant.idCard(this.data.idCard)) {
          wx.showToast({
            title: '身份证不正确',
            icon: 'none',
          })
          return;
        }
      } else {
        wx.showToast({
          title: '身份证号为必填项',
          icon: 'none',
        })
        return;
      }
    }

    if (this.data.userName == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none',
      })
      return;
    }


    if (this.data.localName == '') {
      wx.showToast({
        title: '请选择小区',
        icon: 'none',
      })
      return;
    }
    



    // var phone = that.data.phoneNum;
    // if (!(/^1[34578]\d{9}$/.test(phone))) {
    //   wx.showToast({
    //     title: '手机号码有误，请重填',
    //     icon: 'none',
    //   })
    //   return;
    // } 

    var that = this;
    if (that.data.photoPath == "/images/img_add.png") {
      wx.showToast({
        title: '需要上传照片',
        icon: 'none',
      })
      return;
    }

    wx.showLoading({
      title: '请稍后',
    })

    wx.request({
      url: Constant.BASEURL + Constant.IS_ID_USED + "&key=" + that.data.personKey,
      method: "GET",
      success(res) {
        console.log(res.data)
        if (res.data.respCode == "0") {
          console.log("bbb", that.data.userType)
          if (that.data.userType == "visitor"){
            wx.request({
              url: Constant.BASEURL + Constant.USER_VISITOR_URL,
              method: 'POST',
              data: {
                "id": that.data.personId, "keyid": that.data.personKey, "personname": that.data.userName, "persontype": "98", "openid": that.data.openid, "personphoto": that.data.picBase64, "estarttime": that.data.startTime, "eendtime": that.data.endTime, "myopenid": app.globalData.openid, "unitno": that.data.userOrgCodelList[that.data.localvalue]
              },
              success: function (res) {
                console.log(res.data)
                if (res.data.respCode == "0") {
                  wx.showModal({
                    title: '恭喜',
                    content: '添加访客成功!',
                    showCancel: false,
                    success: function () {
                      wx.navigateBackMiniProgram()
                    }
                  })

                } else {
                  // wx.showToast({
                  //   title: "添加失败："+res.data.message,
                  //   icon: 'none'
                  // })
                  wx.showModal({
                    title: '提示',
                    content: "添加失败：" + res.data.messag,
                  })
                }
                wx.hideLoading();
              },
              fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                  title: '请求失败,请检查网络',
                  icon: 'none',
                })
                console.log('请求失败')
              }
            })

          }else{


            wx.request({
              url: Constant.BASEURL + Constant.LONG_USER_URL,
              method: 'POST',
              data: {
                "id": that.data.personId, "keyid": that.data.personKey, "personname": that.data.userName, "personrelation": that.data.role, "openid": that.data.openid, "personphoto": that.data.picBase64, "myopenid": app.globalData.openid, "personidcardno": that.data.idCard, "unitno": that.data.userOrgCodelList[that.data.localvalue]
              },
              success: function (res) {
                console.log(res.data)
                if (res.data.respCode == "0") {
                  wx.showModal({
                    title: '恭喜',
                    content: '添加亲属成功!',
                    showCancel: false,
                    success: function (res) {
                      if(res.confirm){
                        console.log('图片：')
                        console.log(that.data.picBase64)
                      }
                      wx.navigateBackMiniProgram()
                    }
                  })

                } else {
                  wx.showModal({
                    title: '提示',
                    content: "添加失败：" + res.data.messag,
                  })
                  // wx.showToast({
                  //   title: "添加失败：" + res.data.message,
                  //   icon: 'none'
                  // })
                }
                wx.hideLoading();
              },
              fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                  title: '请求失败,请检查网络',
                  icon: 'none',
                })
                console.log('请求失败')
              }
            })
          }
          


        }else{
          wx.showModal({
            title: '提示',
            content: '该链接已被使用，请业主重新分享',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateBackMiniProgram()
              }
            }
          })
        }
      },
      fail(err) {
        console.log(err)
        wx.showToast({
          title: '系统错误',
          icon: 'none'
        })
      }
    })
    
  }
})

var encryptedData;
var iv;
function getOpenId(res, code) {
  //console.log({ encryptedData: res.encryptedData, iv: res.iv, code: code })
  //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
  wx.request({
    url: Constant.BASEURL + Constant.USER_LOGIN_URL + '&encryptedData=' + res.encryptedData
      + '&iv=' + res.iv + '&code=' + code,//自己的服务接口地址
    method: 'GET',
    // header: {
    //   'content-type': 'application/x-www-form-urlencoded'
    // },
    // data: { encryptedData: res.encryptedData, iv: res.iv, code: code },
    success: function (res) {
      console.log(res.data)
      app.globalData.openid = res.data.openId;

      //4.解密成功后 获取自己服务器返回的结果
      if (res.data.status == 1) {
        var result = res.data.msg;
        console.log(result)
      } else {
        console.log('解密失败')
      }

    },
    fail: function () {
      console.log('系统错误')
    }
  })
}
function picToBase64(path, that) {
  let manager = wx.getFileSystemManager();
  manager.readFile({
    filePath: path,
    encoding: 'base64',
    success: function (res) {
      console.log("编码base64成功")
      that.data.picBase64 = res.data;
    },
    fail: function (res) {
      console.log(res)
    }
  })
}
